package com.jhy.suixianglu.daima20221213;

import com.jhy.suixianglu.daima20221212.ListNode;

/**
 * 删除元素 不用虚拟头节点
 */
public class RemoveLinkedElement2 {
    public ListNode removeElements(ListNode head, int val) {
        // 删除头节点 这里应该是while 循环 而不是if
        while (head != null && head.val == val){
            head = head.next;
        }
        // 不删除头节点
        if(head == null){
            return head;
        }
        ListNode pre = head;
        ListNode cur = head.next;
        while(cur != null){
            if(cur.val == val){
                pre.next = cur.next;
            }else {
                pre = cur;
            }
            cur = cur.next;
        }
        return  head;
    }
}
